package com.formiaomiao.demain.service.impl;

import com.corundumstudio.socketio.SocketIOClient;
import com.formiaomiao.demain.dao.OpinionDao;
import com.formiaomiao.demain.model.OpinionBean;
import com.formiaomiao.demain.model.Result;
import com.formiaomiao.demain.service.OpinionService;
import com.formiaomiao.demain.socket.MessageEventHandler;
import com.formiaomiao.demain.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service(value = "opintionService")
public class OpinionServiceImpl implements OpinionService {

    @Autowired
    private OpinionDao opinionDao;//这里会报错，但是并不会影响
    @Autowired
    private JavaMailSender mailSender;

    @Transactional(value = "demain")
    @Override
    public Result<String> upOpinion(OpinionBean opinionBean) {
        if(opinionDao.upOpinion(opinionBean)==0){
            return ResultUtil.error(20,"意见反馈失败");
        }else{
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SimpleMailMessage message = new SimpleMailMessage();
                    message.setFrom("1013455890@qq.com");
                    message.setTo("1013455890@qq.com");
                    message.setSubject("意见反馈");
                    message.setText(opinionBean.getOpinion());
                    mailSender.send(message);
                    SocketIOClient client = MessageEventHandler.webSocketMap.get(opinionBean.getMac());
                    client.sendEvent("messageevent","{\"data\":\"已经收到您的意见\"}");
                }
            }).start();
            return ResultUtil.success("意见反馈成功");
        }
    }
}
